package com.example.tianyutong.qanda.ui.page_4;

import android.content.Context;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.widget.Toast;

import com.example.http.HttpUtils;
import com.example.tianyutong.qanda.R;
import com.example.tianyutong.qanda.base.BaseFragment;
import com.example.tianyutong.qanda.base.BaseViewModel;
import com.example.tianyutong.qanda.bean.wanandroid.BaseResultBean;
import com.example.tianyutong.qanda.databinding.FragmentAndroidBinding;
import com.example.tianyutong.qanda.http.HttpClient;
import com.example.tianyutong.qanda.ui.MainActivity;
import com.example.tianyutong.qanda.ui.bean.PageInfo;
import com.example.tianyutong.qanda.ui.bean.QuestionUser;
import com.example.tianyutong.qanda.ui.page_4.adapter.MyQuestionAdapter;
import com.example.tianyutong.qanda.utils.RefreshHelper;

import java.util.List;

import io.reactivex.Observable;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;
import me.jingbin.library.ByRecyclerView;
import me.jingbin.library.decoration.SpacesItemDecoration;

/**
 * 我的问题
 */
public class QuestionFragment extends BaseFragment<BaseViewModel, FragmentAndroidBinding> {

    private static final String TAG = "QuestionFragment";
    private static final String TYPE = "mType";
    private String mType;
    private boolean mIsPrepared;
    private boolean mIsFirst = true;
    private MyQuestionAdapter adapter;//这些adapter是每个大fragment都有一个，在initRecyclerView里使用
    private MainActivity activity;

    private int page = 1;


    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        activity = (MainActivity) context;
    }

    public static QuestionFragment newInstance(String type) {
        QuestionFragment fragment = new QuestionFragment();
        Bundle args = new Bundle();
        args.putString(TYPE, type);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //当Activity类动态加载fragment时可以通过fragment的setArguments()传入值,在上面的newInstance里
        // 并在fragment类中通过fragment的getArguments()方法获得传入的值
        if (getArguments() != null) {
            mType = getArguments().getString(TYPE);
        }
    }

    @Override
    public int setContent() {
        return R.layout.fragment_android;
    }//这是给基类的onCreateView方法传值用的

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);

        initRecyclerView();
        // 准备就绪
        mIsPrepared = true;
        showLoading();
        loadAndroidData();
    }

    @Override
    protected void loadData() {
        if (!mIsPrepared || !mIsVisible || !mIsFirst) {
            return;
        }
        showLoading();
        loadAndroidData();
        mIsFirst = false;
    }

    private void initRecyclerView() {
        adapter = new MyQuestionAdapter();
        // 加了分割线，滚动条才会置顶
        SpacesItemDecoration itemDecoration = new SpacesItemDecoration(activity, SpacesItemDecoration.VERTICAL, 1);
        itemDecoration.setDrawable(R.drawable.shape_transparent);//就是全透明的一条线
        //xrvAndroid是fragment_android中ByRecyclerView的id名xrv_android
        RefreshHelper.initLinear(bindingView.xrvAndroid, false).addItemDecoration(itemDecoration);
        bindingView.xrvAndroid.setAdapter(adapter);
        bindingView.xrvAndroid.setOnRefreshListener(new ByRecyclerView.OnRefreshListener() {
            @Override
            public void onRefresh() {
                page = 1;
                loadAndroidData();
            }
        });
        bindingView.xrvAndroid.setOnLoadMoreListener(new ByRecyclerView.OnLoadMoreListener() {
            @Override
            public void onLoadMore() {
                page++;
                loadAndroidData();
            }
        }, 300);
    }

    private void loadAndroidData() {
        Observable<BaseResultBean<PageInfo<QuestionUser>>> observable = null;
        if ("my".equals(mType)) {
            //我的
            observable = HttpClient.Builder.getQAndAServer().getMyQuestions(page, HttpUtils.per_page_more);
        } else if ("like".equals(mType)){
            //我的收藏
            observable = HttpClient.Builder.getQAndAServer().getMyCollectionList(page, HttpUtils.per_page_more);
        }else {
            //他人
            observable = HttpClient.Builder.getQAndAServer().getAllQuestions(page, HttpUtils.per_page_more);
        }

        observable
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<BaseResultBean<PageInfo<QuestionUser>>>() {
                    @Override
                    public void onSubscribe(Disposable d) {
                    }

                    @Override
                    public void onNext(BaseResultBean<PageInfo<QuestionUser>> bean) {
                        PageInfo<QuestionUser> pageInfo = bean.getData();
                        List<QuestionUser> list = pageInfo.list;
                        if (list != null && list.size() > 0) {
                            if (page == 1) {
                                showContentView();
                                adapter.setNewData(list);
                            } else {
                                adapter.addData(list);
                            }
                            bindingView.xrvAndroid.loadMoreComplete();
                            if (!pageInfo.hasNextPage){
                                bindingView.xrvAndroid.loadMoreEnd();
                            }
                        } else {
                            if (page == 1) {
                                showEmptyView("暂无数据\n点击刷新");
                            } else {
                                bindingView.xrvAndroid.loadMoreEnd();
                            }
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        showError();
                        Toast.makeText(getContext(), "请检查网络", Toast.LENGTH_SHORT).show();
                    }

                    @Override
                    public void onComplete() {

                    }
                });

    }

    /**
     * 加载失败后点击后的操作
     */
    @Override
    protected void onRefresh() {
        loadAndroidData();
    }
}
